﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public partial class admin_ThongKeDoanhThu : System.Web.UI.Page
{
    private DataSet objOrderDS;
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set the title of the page
        this.Title = TGDDConfiguration.SiteName +
                " : Thống kê doanh thu";
        // associate the check boxes with their buttons
        Utilities.TieButton(this.Page, startDateTextBox, byDateGo);
        Utilities.TieButton(this.Page, endDateTextBox, byDateGo);
    }
    
    // list the orders that happened between specified dates
    protected void byDateGo_Click(object sender, EventArgs e)
    {
        // check if the page is valid (we have date validator controls)
        if (startDateTextBox.Text + endDateTextBox.Text != "")
        {
            // get the dates
            string[] supportedFormats = new String[] { "dd/MM/yyyy", "MM/dd/yyyy", "MM/dd/yy", "ddMMMyyyy", "dMMMyyyy" };
            DateTime startDate = DateTime.ParseExact(
                startDateTextBox.Text, supportedFormats,
                System.Globalization.CultureInfo.CurrentCulture,
                System.Globalization.DateTimeStyles.None);

            DateTime endDate = DateTime.ParseExact(
                endDateTextBox.Text, supportedFormats,
                System.Globalization.CultureInfo.CurrentCulture,
                System.Globalization.DateTimeStyles.None);

            if (startDate > endDate)
            {
                errorLabel.Text = "<br />Ngày bắt đầu phải nhỏ hơn ngày kết thúc!";
                grid.DataSource = null;
                grid.DataBind();
                return;
            }

            DonDatHangBUS objOrder = new DonDatHangBUS(TGDDConfiguration.DbConnectionString);
            objOrderDS = objOrder.ThongKeDoanhThu(startDate, endDate);
            grid.DataSource = objOrderDS.Tables[0];

            long doanhthu = 0;
            for(int i=0; i<objOrderDS.Tables[0].Rows.Count; i++)
            {
                DataRow row = objOrderDS.Tables[0].Rows[i];
                doanhthu += long.Parse(row["ThanhTien"].ToString());
            }
            lblDoanhThu.Text = String.Format("{0:#,##0;Nothing}", doanhthu) + " VNĐ"; 
        }
        else
            errorLabel.Text = "<br />Vui lòng nhập vào ngày hợp lệ!";
        // refresh the data grid
        grid.DataBind();
        // no order is selected
        Session["AdminOrderID"] = null;
    }
    
    protected void grid_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Save the ID of the selected order in the session
        Session["AdminOrderID"] = grid.DataKeys[grid.SelectedIndex].Value.ToString();
    }
}
